package Server.Game;

import java.util.ArrayList;
import java.util.Iterator;

import Server.Sessions.ClientSession;
import Server.Sessions.OutboundMessages;

import shared.Messages.BeginMessage;
import shared.Player.Player;



public class GameStart extends Thread {
	ArrayList<ClientSession> GameClientsToGame = new ArrayList<ClientSession>();
	OutboundMessages outQueue;
	int GameNo = 0;
	int count = 0;
	Player p0;
	Player p1;
	public GameOK gameOK;

	
	public GameStart(ArrayList<ClientSession> GameClients, OutboundMessages outQueue, 
			int GameNo){
		GameClientsToGame.addAll(GameClients);
		this.outQueue = outQueue;
		this.GameNo = GameNo;
		start();
	
		}
	
	public void run(){
		Iterator<ClientSession> itr = GameClientsToGame.iterator();
		while(itr.hasNext()){
			ClientSession cli = (ClientSession) itr.next();
			switch(count){
			case 0: 
				p0 = cli.player = new Player(cli.getName(), GameNo, 1);
				break;
			case 1: 
				p1 = cli.player = new Player(cli.getName(), GameNo, 2);
				break;		
			}
			count++;
			if(count == 2){
				outQueue.addMessage(new BeginMessage(GameNo, p0.name, p1.name, p0.playerID, p1.playerID));
				break;
			}
		}
		while(true){
			try{
				Thread.sleep(100);
			}catch (InterruptedException e){
				System.out.println("Sleep katkestatud!");
				break;
			}
			if(playersReady()){
				gameOK = new GameOK(outQueue, GameNo, p0, p1);
				break;
			}
		}
	}

	private boolean playersReady() {
		Iterator<ClientSession> itr = GameClientsToGame.iterator();
		while(itr.hasNext()){
			ClientSession cli = (ClientSession) itr.next();
			if(cli.IsReady == false){
				return false;
			}
		}
		return true;
	}
	
	}
